﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.Extensions.Configuration;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IServices;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.ViewModels.WebApi;
using BestTrader.Cms.WebApi.Validation;
using FluentValidation.Results;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace BestTrader.Cms.WebApi.Controllers.v1
{
    /// <summary>
    /// 出入金管理
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class InOutCashController : BaseController
    {

        private readonly IUCInOutCashService _service;
        private readonly ILogger<InOutCashController> _logger;
        private readonly IMapper _mapper;
        private readonly IUCAlipayInCashService _aliPayservice;
        private readonly IConfiguration _configuration;
        private readonly IManagerService _managerService;

        public InOutCashController(
            IUCInOutCashService service,
            ILogger<InOutCashController> logger,
            IMapper mapper,
            IUCAlipayInCashService aliPayservice,
            IManagerService managerService,
            IConfiguration configuration)
        {
            _service = service;
            _logger = logger;
            _mapper = mapper;
            this._aliPayservice = aliPayservice;
            _managerService = managerService;
            _configuration = configuration;

        }
        /// <summary>
        /// [10001] 出入金记录
        /// </summary>
        /// <param name="input"></param>
        /// <remarks>
        /// CurrentIdAndRoleIdInput :
        /// INPUT: /CurrentIdAndRoleIdInput
        /// {
        ///     "CurrentId": "89", // 用户ID
        ///     "RoleId": "6", // 角色
        ///     "key":"", //关键字搜索
        ///     "state":"" （出金： 0：待审核；1：审核通过；2：审核失败；）（入金： 0：待审核；1：入金完成；2：入金失败；） 空值为全部数据
        ///     "InOutType":"20", 记录类型 10 出金  20 入金  默认入金记录
        /// }
        /// OUTPUT /OutCoinUserModel
        ///{
        ///"id": 1,
        ///"userManagerId": 27,
        ///"rmmfUserId": 12,
        ///"userBankType": "民生银行",
        ///"userBankProvince": "上海",
        ///"userRealName": "BT002",
        ///"userName": "BT002",
        ///"userCardNo": "6222222222222222222222222",
        ///"managerRealName": null,
        ///"managerCardNo": null,
        ///"orderNo": "BT00220190222171302",
        ///"moneyType": "USD",
        ///"money": 100,
        ///"rmbMoney": 674.5,
        ///"auditTime": null,
        ///"state": 1,      //状态（出金： 0：待审核；1：审核通过；2：审核失败；）（入金： 0：待审核；1：入金完成；2：入金失败；）
        ///"cashType": 2,   
        ///"cashModel": 1,
        ///"ip": null,
        ///"remark": "用户入金",    
        ///"addManagerId": 27,
        ///"addTime": "2019-02-22T17:13:02.167",
        ///"modifyManagerId": null,
        ///"modifyTime": null,
        ///"isDelete": false
        ///}
        ///</remarks>
        /// <returns></returns>
        [HttpPost("GetInOutCoinRecord")]
#if !DEBUG
        [Authorize]
#endif
        public JsonResult GetInOutCoinRecord(InOutCoinRecordInput input)
        {
            var result = new BaseResult { Success = false };
            var data = new TableDataModel { data = "", count = 0 };
            var item = new CurrentIdAndRoleIdInput()
            {
                CurrentId = input.CurrentId.ToInt32(),
                RoleId = input.RoleId.ToInt32()
            };
            CurrentIdAndRoleIdValidation validationRules = new CurrentIdAndRoleIdValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                if (input.Page == 0) input.Page = 1;
                if (input.Limit == 0) input.Limit = 10;

                var model = _mapper.Map<InOutCoinRecordRequestModel>(input);
                //10 出金  20入金
                if (input.InOutType == 20)
                {
                    data = _service.LoadInCoinRecordData(model, input.CurrentId, input.RoleId);
                }
                else
                {
                    data = _service.LoadOutCoinRecordData(model, input.CurrentId, input.RoleId);
                }
                result.Success = true;

            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return Json<Object>(data, result.Success, result.ResultCode, result.ResultMsg);

        }
        /// <summary>
        /// [10002] 获取用户入金相关信息（汇率等）
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetInCoinUserData")]
        [Authorize]
        public JsonResult GetInCoinUserData(CurrentIdAndRoleIdInput input)
        {
            var result = new TableDataResult<InCoinUserModel>() { Success = false };
            CurrentIdAndRoleIdValidation validationRules = new CurrentIdAndRoleIdValidation();
            ValidationResult results = validationRules.Validate(input);
            if (results.IsValid)
            {
                result = _service.LoadInCoinUserData(input.CurrentId.ToString(), input.RoleId.ToString());
                if (result.ResultCode == 200) result.Success = true;

            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return Json<Object>(result.Data, result.Success, result.ResultCode, result.ResultMsg);

        }
        /// <summary>
        /// [10003] 用户入金
        /// </summary>
        /// <remarks>
        ///OUTPUT/
        ///{
        ///"id": 30,
        ///"userBankType": "中国银行",
        ///"userBankProvince": "北京",
        ///"userRealName": "赵志超",
        ///"userName": "TEST100065",
        ///"userCardNo": "62111111111111111111",
        ///"managerRealName": null,         //管理方姓名
        ///"managerCardNo": null,           //管理方银行卡号
        ///"orderNo": "TEST10006520190228114244",   //订单编号
        ///"rmbMoney": 6745,
        ///"displayRMBMoney": "6745.00元",
        ///"cashModel": 1,    // 出入金方式： 1.线下； 2. 支付宝； 3.银行卡；
        ///"qrCode": null,    //二维码信息 在线支付二维码
        ///imgHost:"url",      //二维码地址
        ///"times": null    //线上支付 倒计时
        ///}
        /// </remarks>
        /// <returns></returns>
        [HttpPost("AddOrModifyInCoin")]
#if !DEBUG
        [Authorize]
#endif
        public JsonResult AddOrModifyInCoin(AddInCoinInput input)
        {
            var result = new BaseResult { Success = false };
            InCashValidation validationRules = new InCashValidation();
            ValidationResult results = validationRules.Validate(input);
            var data = new ConfirmInCashModel();
            if (results.IsValid)
            {
                var model = _mapper.Map<InCashModel>(input);
                var UserId = model.ManagerId.ToString();
                var ManagerData = _managerService.GetManagerTableById(UserId);
                //判断有没有风软ID
                if (ManagerData.Data != null)
                {
                    model.RmmfUserId = ManagerData.Data?.RmmfUserId;
                    var resultData = _service.AddOrModifyInCoin(model);
                    if (resultData.ResultCode == 200)
                    {
                        data = _service.GetInCoinById(resultData.Data, UserId);
                        result.Success = true;

                        //支付宝线上入金
                        if (resultData.Data > 0 && data != null && model.CashModel == 2 && model.CashType == 3)
                        {
                            var model2 = _service.GetInCoinById(resultData.Data, input.ManagerId.ToString());
                            model2.ImgHost = _configuration["YunpayQRCodeImgHost"];
                            var ip4 = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
                            var data2 = _aliPayservice.AddYunpayQRCode(model2, ip4, input.ManagerId.ToString());
                            if (data2 == null)
                            {
                                result.Success = false;
                                result.ResultCode = 106;
                                result.ResultMsg = "支付宝获取支付二维码失败";
                                return Json<Object>(model2, result.Success, result.ResultCode, result.ResultMsg);
                            }
                            else
                            {
                                return Json<Object>(model2, result.Success, result.ResultCode, result.ResultMsg);

                            }
                        }
                    }
                    else
                    {
                        result = resultData;
                    }
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }

            return Json<Object>(data, result.Success, result.ResultCode, result.ResultMsg);
        }
        /// <summary>
        /// 获取订单支付详细(第三方支付宝)
        /// </summary>
        [HttpPost("GetYunPayOrderState")]

        public JsonResult GetYunPayOrderState(GetAliPayInCoinQRCodeInput input)
        {
            var result = new BooleanResult();

            var ip4 = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
             result = _aliPayservice.GetOrderStateById(input.InCashId, ip4, input.ManagerId);
            if (result.ResultMsg != null)
            {
                if (result.ResultCode == 200)
                {
                    if (result.Data)
                    {
                    }
                    else
                    {
                        result.ResultCode = 107;
                    }
                }
                else
                {
                    result.ResultCode = 107;
                }
            }
            else
            {
                result.ResultCode = 107;
            }

            return Json<Object>(result.Data, result.Success, result.ResultCode, result.ResultMsg);

        }

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="inCoinId"></param>
        ///// <returns></returns>
        //[HttpPost("ConfirmAliPayInCoin")]
        //public JsonResult ConfirmAliPayInCoin(ConfirmAliPayInCoinInput input)
        //{
        //    var result = new BaseResult() { Success = false };
        //    var model = _service.GetInCoinById(input.InCashId, input.ManagerId);
        //    var ip4 = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
        //    var data  = _aliPayservice.AddYunpayQRCode(model, ip4, input.ManagerId);

        //    return Json<Object>(result);
        //}
        /// <summary>
        /// [10004] 用户完成入金
        /// </summary>
        /// <param name="input"></param>
        /// <remarks>
        /// </remarks>
        /// 
        [HttpPost("ConfirmInCoin")]
        [Authorize]
        public JsonResult ConfirmInCoin(ConfirmInCashManagerIdModel input)
        {
            var result = new BaseResult()
            {
                Success = false
            };
            ConfirmInCashValidation validationRules = new ConfirmInCashValidation();
            ValidationResult results = validationRules.Validate(input);
            if (results.IsValid)
            {
                var model = new ConfirmInCashModel
                {
                    Id = input.Id,
                    ManagerCardNo = input.ManagerCardNo,
                    ManagerRealName = input.ManagerRealName
                };
                result = _service.AuditConfirmInCoin(model, input.ManagerId.ToString());
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }

            return Json<Object>("", result.Success, result.ResultCode, result.ResultMsg);

        }



        /// <summary>
        /// [10005] 【出金】获取用户出金前的相关信息
        /// </summary>
        /// <param name="input"></param>
        /// <remarks>
        /// CurrentIdAndRoleIdInput :
        /// INPUT: /CurrentIdAndRoleIdInput
        /// {
        ///     "CurrentId": "89", // 用户ID
        ///     "RoleId": "6", // 角色
        /// }
        /// OUTPUT /OutCoinUserModel
        ///{
        ///  "managerId": 89,
        ///  "rmmfUserId": null,        //风软UserID
        ///  "userName": "TEST100065",
        ///  "realName": "赵志超",
        ///  "bankCard": "****1111",        //银行卡号
        ///  "totalMoney": 0.00000000,      //可提现余额
        ///  "money": 0.0,                  //提现金额（美元） 
        ///  "rmbMoney": 0.0,                //提现金额（人民币） 
        ///  "exchangeRate": 6.74500000     //汇率
        /// }
        /// </remarks>
        /// <returns></returns>
        [HttpPost("GetOutCoinUserData")]
        [Authorize]
        public JsonResult GetOutCoinUserData(CurrentIdAndRoleIdInput input)
        {
            var result = new TableDataResult<OutCoinUserModel>() { Success = false };
            CurrentIdAndRoleIdValidation validationRules = new CurrentIdAndRoleIdValidation();
            ValidationResult results = validationRules.Validate(input);
            if (results.IsValid)
            {
                result = _service.LoadOutCoinUserData(input.CurrentId.ToString(), input.RoleId.ToString());
                if (result.ResultCode == 200) result.Success = true;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }

            return Json<Object>(result.Data, result.Success, result.ResultCode, result.ResultMsg);

        }

        /// <summary>
        /// [10006] 【出金】用户申请出金
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost("AddOrModifyOutCoin")]
        public JsonResult AddOrModifyOutCoin(OutCashManagerIdModel input)
        {
            var result = new BaseResult() { Success = false };

            var model = new OutCashModel
            {
                ManagerId = input.ManagerId,
                RmmfUserId = input.RmmfUserId,
                Money = input.Money
            };
            OutCashValidation validationRules = new OutCashValidation();
            ValidationResult results = validationRules.Validate(model);
            if (results.IsValid)
            {
                result = _service.AddOrModifyOutCoin(model);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return Json<Object>("", result.Success, result.ResultCode, result.ResultMsg);


        }


    }
}
